package com.spzx.common.rabbitmq.service;

import com.spzx.common.rabbitmq.domain.SpzxMqCorrelationData;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RabbitTemplate rabbitTemplate;
    //发送mq消息的工具方法
    public void sendMsg(String exchange,String routingKey , Object message){
        sendMsg(exchange,routingKey,message,true,3);
    }
    public void sendMsg(String exchange,String routingKey , Object message , boolean isRetry){
        sendMsg(exchange,routingKey,message,isRetry,3);
    }
    public void sendMsg(String exchange,String routingKey , Object message , boolean isRetry,
                        int limit){
        SpzxMqCorrelationData spzxMqCorrelationData = new SpzxMqCorrelationData();
        spzxMqCorrelationData.setExchange(exchange);
        spzxMqCorrelationData.setRoutingKey(routingKey);
        spzxMqCorrelationData.setMessage(message);
        spzxMqCorrelationData.setRetry(isRetry);
        spzxMqCorrelationData.setRetryLimit(limit);
        spzxMqCorrelationData.setRetryCount(1);//第一次发送消息
        //发送消息之前，将重试对象 k-v映射存到redis中
        redisTemplate.opsForValue().set("spzx:mq:retry:dataId:"+spzxMqCorrelationData.getId()
                , spzxMqCorrelationData);
        rabbitTemplate.convertAndSend(exchange,
                routingKey,
                message,
                spzxMqCorrelationData);
    }
}
